﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Grishko.DataTier.SqlSentence;
using Grishko.UI;
using Grishko.DataTier;

public partial class Ctl_ctlFiltereditor : System.Web.UI.UserControl,IFilterEditor  
{
    public Func<bool> SaveMethod;
    
    public string GetTxt_WordType(Word obj)
    {
        return Word.ConvertWordTypesToTxt(obj.WordType).ToUpper();   
        
    }


    public string GetTxt_Field(Word obj)
    {
        if (string.IsNullOrEmpty(obj.TxtKey))
            return string.Empty;
        return obj.TxtKey;
    }

    public string GetTxt_Operation(Word Value)
    {

        if (null == Value.Operator)
                        return string.Empty;
        return Word.ConvertOperatorTypesToTxt(Value.Operator);
        
    }

  

    public string GetTxt_Value(Word obj)
    {
        if (null == obj.Value)
            return string.Empty;

        return obj.Value.ToString();
    }

    Func<ListViewDataItem, bool> LvUpdCmd = null;    
    /// <summary>
    /// источник данных
    /// </summary>
    /// <returns></returns>
    //public Func<ScriptEngine> GetWhere;
    
    ScriptEngine __ListWhere = null;
    protected ScriptEngine _ListWhere
    {
        get {
            if (null != __ListWhere)
                    return __ListWhere;

            if (null == DataSource)
                            return null;

            if (null == DataSource())
                            return null;

            __ListWhere = DataSource().Where;

            return __ListWhere;
        }
    }

   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (null != lvWhere.EditItem)
            InitEditControl();
        
       

    }

    /// <summary>
    /// Инициализировать редактируемый контрол источниками данных 
    /// </summary>
    private void InitEditControl()
    {
        _ListWhere.Sentence.WordList.Reset();
        Ctl_ctlFilterItemEditor ctl = (Ctl_ctlFilterItemEditor)lvWhere.EditItem.FindControl("ctlFilterItemEditor1");
        ctl.ListWhereSource = _ListWhere;

        HiddenField hf = (HiddenField)lvWhere.EditItem.FindControl("hfSentenceWordId");

        for (int i = 0; i < _ListWhere.Sentence.WordList.Count ; i++) 
        {
            if (hf.Value == _ListWhere.Sentence.WordList[i].ID)
            {
                ctl.SentenceWord =(Word) _ListWhere.Sentence.WordList[i];
                _ListWhere.Sentence.WordList.Reset();
                break;
            }
        }        
    }

    protected  WhereSentenceWord GetItemSource(object Item)
    {
        return (WhereSentenceWord)Item;

    }
  
    public override void DataBind()
    {
        if(null==_ListWhere )
            return ;
        lvWhere.DataSource = _ListWhere.Sentence .WordList;
        lvWhere.DataBind();

    }

    protected void btnRemoveRow_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton btn = (ImageButton)sender;
        string s = btn.CommandArgument;
        _ListWhere.Sentence.WordList.Remove(s);
        _ListWhere.Sentence.WordList.Reset();
        DataBind();
        if (null != ImChange)
                        ImChange();
        ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), "HideAlert();", true);        

    
         
    }
    
    protected void btnAddRecord_Click(object sender, EventArgs e)
    {
        Word w = new Word() { WordType = Word.WordTypes.AND };
        _ListWhere.Sentence.WordList.Add(w);
        lvWhere.EditIndex = _ListWhere.Sentence .WordList .Count - 1;
        _ListWhere.Sentence.WordList.Reset();
        DataBind();
    }

    /// <summary>
    /// Сформировать значение 
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    private bool UpdateItem(ListViewDataItem item)
    {
        Ctl_ctlFilterItemEditor i = (Ctl_ctlFilterItemEditor)lvWhere.EditItem.FindControl("ctlFilterItemEditor1");
        i.ListWhereSource = _ListWhere;
        HiddenField hf = (HiddenField)lvWhere.EditItem.FindControl("hfSentenceWordId");
        i.FixedSentenceValue();
        if (null != SaveMethod)
                SaveMethod();

        if (null != ImChange)
                        ImChange();
      return true;
    }    

    protected void lvWhere_ItemCommand(object sender, ListViewCommandEventArgs e)
    {

        if (string.Empty == e.CommandName) return;
        ListView lv = (ListView)sender;
        switch (lv.ID)
        {

            case "lvWhere":
                LvUpdCmd = UpdateItem;
                break;
        }

        switch (e.CommandName)
        {
            case "Edit":
                {
                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;
                    break;
                }
            case "Insert":
                {
                    break;
                }
            case "Update":
                {
                    if (LvUpdCmd((ListViewDataItem)e.Item)) 
                        lv.EditIndex = -1;                 
                    break;
                }
            case "Delete":
                {                    
                    break;
                }
        }

        _ListWhere.Sentence.WordList.Reset();
        lvWhere.DataSource = _ListWhere.Sentence.WordList;
        DataBind();
        
    }
   
    protected void lvWhere_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
   
    protected void lvWhere_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }


    #region Члены IFilterEditor

    public Func<OutdoorLib.BaseEntity.Infrastructure.Filter> DataSource {get;set;}

    public Func<bool> ImChange    { get; set;}            

    #endregion
}
